package data.news;

import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Keyword{
	public static Pattern NODE_PATTERN    = Pattern.compile("<(\\w*) *(.*?) *> (.*?) </\\w*>");
	public static int NAME_GROUP = 1;
	public static int ATTR_GROUP = 2;
	public static int CONTENT_GROUP = 3;
	public static Pattern TAG_PATTERN = Pattern.compile("/\\S*");//not /whitespace sequence
	public static Pattern ATT_KEY_SPLITER = Pattern.compile(" = \".*?\" *");
	public static Pattern ATT_VAL_SPLITER = Pattern.compile(" *[^ ]* = ");
	
	private long articleID = -1;
	public long getArticleID() {
		return articleID;
	}

	private String string = null;
	private Matcher matcher = null;
	private String content = null;
	public Keyword(String string, long articleID){
		//<...> XX/YY </..>
		this.articleID = articleID;
		this.string = string;
		this.matcher = NODE_PATTERN.matcher(string);
		this.matcher.matches();
	}
	public String getNode(){
		return string;
	}
	public String getTagName(){
		return matcher.group(NAME_GROUP);
	}
	public String getWord(){
		if (content == null) {
			content = TAG_PATTERN.matcher(matcher.group(CONTENT_GROUP)).replaceAll("");
			content = Article.replaceAllWithGroups(Article.goLeftPattern,     content,  1);
		}
		return content;
	}
	public void getAttris(Map<String, String> map){
		map.clear();
		String attString = matcher.group(ATTR_GROUP);
		String[] attTokens = ATT_KEY_SPLITER.split(attString);
		String[] attValues = ATT_VAL_SPLITER.split(attString);
		for(int tokenIdx = 0; tokenIdx<attTokens.length; tokenIdx++){
			map.put(attTokens[tokenIdx], 
					attValues[tokenIdx+1].substring(1, attValues[tokenIdx+1].length()-1));
		}
	}
	public String getAttrValue(String att){
		att = att.trim()+" ";
		String attString = matcher.group(ATTR_GROUP);
		int startIdx = attString.indexOf(att);
		if (startIdx < 0) {
			startIdx = attString.indexOf(att.toUpperCase());
		}
		if (startIdx<0) {
			return null;
		}
		attString = attString.substring(startIdx+att.length()+3);
		return attString.substring(0, attString.indexOf("\""));
	}
	public Map<String, String> getAttris(){
		Map<String, String> map = new TreeMap<String, String>();
		getAttris(map);
		return map;
	}
	public static void main(String[] args) {
		Keyword n = new Keyword("<pn category = \"GENERAL\" score0 = \"1\" > Better/JJR graphics/NNS ,/, such/JJ as/IN snazzier/JJR </pn>",1);
		System.out.println(">"+n.getTagName()+"<");
		System.out.println(n.getAttrValue("category"));
		Map<String, String> map = new TreeMap<String, String>();
		map = n.getAttris();
		for(String str : map.keySet()){
			System.out.println(str+"<>"+map.get(str));
		}
		System.out.println(n.getWord());
	}
}